package com.v1.video.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.iss.view.common.ToastAlone;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXVideoObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.v1.video.AppContext;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.H5Info;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.VrLiveMoneyEntity;
import com.v1.video.domain.VrLivePayEntity;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;
import com.v1.video.view.CustomShareSheetDialog;
import com.v1.video.view.CustomShareSheetDialog.OnShareSheetItemClick;
import com.v1.video.view.jsbridge.BridgeHandler;
import com.v1.video.view.jsbridge.BridgeWebView;
import com.v1.video.view.jsbridge.BridgeWebViewClient;
import com.v1.video.view.jsbridge.CallBackFunction;
import com.v1.video.view.jsbridge.DefaultHandler;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;

public class WebViewActivity4 extends BaseActivity {
	private final String TAG = "WebViewActivity4";
	private FrameLayout videoview;// 全屏时视频加载view
	private BridgeWebView videowebview;
	private Boolean islandport = true;// true表示此时是竖屏，false表示此时横屏。
	private View xCustomView;
	private xWebChromeClient xwebchromeclient;
	private String url = "http://www.v1.cn/active/v1cnLive.shtml";
	private String commodityid = "";
	private WebChromeClient.CustomViewCallback xCustomViewCallback;
	private ProgressDialog progressBar=null;
	public static final int STATE_TYPE_0 = 0;//可以分享
	public static final int STATE_TYPE_1 = 1;//不分享，目前就是玩游戏和启动页的那个广告进入的时候不分享
	public static final String FLAG_TITLE = "title";
	public static final String FLAG_TYPE = "type";
	AppContext mContext;
	private final int STATE_JS = 0x0001;
	private int type = 0;
	TextView mTvTitle = null;
	
	public static final int STATE_TYPE_2 = 2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉应用标题
		/*
		 * getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
		 * WindowManager.LayoutParams.FLAG_FULLSCREEN);
		 */		
		setContentView(R.layout.activity_webview4);
//		String model=android.os.Build.MODEL;
//		Logger.i(TAG, "model111111111111=="+model);
//		if(model.startsWith("GT") || model.startsWith("SM") || model.startsWith("SCH") || model.startsWith("SGH")
//				|| model.startsWith("SPH") || model.startsWith("STH")){
//			getWindow().setFlags( WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); 
//		}
		mContext = (AppContext)getApplicationContext();
		initwidget();
		initListener();
		//videowebview.loadUrl(url);
	}	

	private void initListener() {
		findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		findViewById(R.id.iv_right).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showShareBack();
			}
		});
//		findViewById(R.id.head_webview_result).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				if (inCustomView()) {
//					hideCustomView();
//				} else {
//					finish();
//				}
//			}
//		});
//		findViewById(R.id.head_webview_shard).setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				showShareBack();
//			}
//		});
	}

//	@JavascriptInterface
	private void initwidget() {
		// TODO Auto-generated method stub
//		if(getIntent().getExtras().containsKey("title")){
//			((TextView) findViewById(R.id.tv_caption)).setText(getIntent().getExtras().getString("title"));
//		}else{
//			((TextView) findViewById(R.id.tv_caption)).setText("详情");
//		}

		mTvTitle = (TextView) this.findViewById(R.id.tv_title);
		progressBar = new ProgressDialog(this);
    	progressBar.setTitle("页面加载中,请稍后...");
//    	progressBar.setMessage("Loading...");
    	progressBar.setMessage("加载中...");
		
		videoview = (FrameLayout) findViewById(R.id.video_view);
		videowebview = (BridgeWebView) findViewById(R.id.video_webview);
		WebSettings ws = videowebview.getSettings();
		/**
		 * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
		 * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
		 * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
		 * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
		 * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
		 * setSupportZoom 设置是否支持变焦
		 * */
		videowebview.getSettings().setDisplayZoomControls(true);
		videowebview.getSettings().setSupportZoom(true);
		videowebview.getSettings().setCacheMode(videowebview.getSettings().LOAD_NO_CACHE);
		videowebview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
		videowebview.setHorizontalScrollBarEnabled(false);
		videowebview.setVerticalScrollBarEnabled(false);	
		videowebview.getSettings().setSupportZoom(false);
	    videowebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
	    videowebview.getSettings().setBuiltInZoomControls(true);//support zoom	    
//	    videowebview.getSettings().setPluginsEnabled(true);//support flash	   
	    videowebview.getSettings().setJavaScriptEnabled(true);
	    
	    videowebview.getSettings().setPluginState(PluginState.ON);  
	    videowebview.getSettings().setUseWideViewPort(true);// 这个很关键
	    videowebview.getSettings().setLoadWithOverviewMode(true);
	    videowebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
	    
        String adLink = getIntent().getStringExtra("adLink");
        commodityid = getIntent().getStringExtra("commodityid");
        title = getIntent().getStringExtra("title");
        type = getIntent().getIntExtra("type", 0);
        if(type == 1){
        	findViewById(R.id.head_webview_shard).setVisibility(View.GONE);
        }
        mTvTitle.setText(title);
        videowebview.setDefaultHandler(new DefaultHandler());//ft_1.25h5交互
        // load a web page
        if(!TextUtils.isEmpty(adLink)){
        	videowebview.loadUrl(adLink+"&APP=android&uid="+LoginInfo.getInstance().getUserId());
        	url = adLink;
//        	videowebview.loadUrl("http://192.168.9.105:81/player/player.html");
        }else{
        	url = "";
        }
//        videowebview.loadUrl("file:///android_asset/calljs1.html");//ft_1.25h5交互
//        videowebview.loadUrl("file:///android_asset/demo.html");//ft_1.25h5交互
//        videowebview.loadUrl("file:///android_asset/player/alive.html");//ft_1.25h5交互
//        videowebview.loadUrl("file:///android_asset/index.html");//ft_6.16交互
//        videowebview.loadUrl("file:///android_asset/VRindex.html?APP=android");//ft_6.16交互
	    Logger.i(TAG, "adLink=="+adLink);
	    
		xwebchromeclient = new xWebChromeClient();
		videowebview.setWebChromeClient(xwebchromeclient);
		
		videowebview.setWebViewClient(new xWebViewClientent(videowebview));//ft_1.25h5交互注释掉了	
		
		H5Info info = new H5Info();
		if(LoginInfo.getInstance().isLogin()){
			info.setIsLogin("1");
			info.setUserId(LoginInfo.getInstance().getUserId());
			info.setUserName(LoginInfo.getInstance().getUserName());			
		}else{
			info.setIsLogin("0");
			info.setUserId("0");
			info.setUserName("0");		
		}
		info.setpCode(Constant.PRODUCT_CODE);
		info.setVersion(Constant.PRODUCT_VERSION);
		
		info.setDeviceId(Constant.DEVICEID);
		//functionInJs//judgeLoginInit//"小鸡小鸭小鸡咯咯蛋"
		videowebview.registerHandler("judgeParForSeeVR", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
//				Logger.i(TAG, "handler = judgeParForSeeVR, data from web = " + data);
//                function.onCallBack("judgeParForSeeVR exe, response data 中文 from Java");
//                showShareBack();
//				Logger.i(TAG, "data=="+data);
				if(commodityid != null && commodityid.length()>0){
				}else{
					int index = data.lastIndexOf("\"");
					Logger.i(TAG, "index=="+index);
					int index1 = data.lastIndexOf("\"", index-1);
					Logger.i(TAG, "index1=="+index1);
					String id = data.substring(index1+1,index);
					Logger.i(TAG, "id=="+id);
					commodityid = id;
				}
				if(LoginInfo.getInstance().isLogin()){
					getMoneyFromServerOfVR();
				}else{
					gotoLogin();
				}
			}
		});
		
		videowebview.registerHandler("videoPlayOfVR", new BridgeHandler() {

			@Override
			public void handler(String data, CallBackFunction function) {
				Logger.i(TAG, "handler = videoPlayOfVR, data from web = " + data);
//                function.onCallBack("videoPlayOfVR exe, response data 中文 from Java");
//				showShareBack();
				Logger.i(TAG, "data=="+data);
				if(commodityid != null && commodityid.length()>0){
				}else{
					int index = data.lastIndexOf("\"");
					Logger.i(TAG, "index=="+index);
					int index1 = data.lastIndexOf("\"", index-1);
					Logger.i(TAG, "index1=="+index1);
					String id = data.substring(index1+1,index);
					Logger.i(TAG, "id=="+id);
					commodityid = id;
				}
				showDialog();
				getDataFromServerForVrLive();
			}

		});
		videowebview.callHandler("judgeLoginForPay", new Gson().toJson(info), new CallBackFunction() {//ft_1.25h5交互
            @Override
            public void onCallBack(String data) {
            	Logger.i(TAG, "functionInJs  return data");
            }
        });
		
		videowebview.send("hello");
		
		ShareSDK.initSDK(this);
		api = WXAPIFactory.createWXAPI(this, Constant.APP_ID);
		api.registerApp(Constant.APP_ID);
		((ImageView)findViewById(R.id.iv_right)).setVisibility(View.VISIBLE);
		((ImageView)findViewById(R.id.iv_right)).setImageResource(R.drawable.petitiondetail_share_selecter);
//		Message msg = handler.obtainMessage();//ft_1.25h5交互
//		msg.what = STATE_JS;
//		handler.sendMessageAtTime(msg, 3000);
	}
	
	private void gotoLogin(){
		Intent intent_login = new Intent(WebViewActivity4.this,
				SettingLoginActivity.class);
		intent_login.putExtra("loginFlag", 2);
		WebViewActivity4.this.startActivity(intent_login);
	}
	
	private void gotoLivePay(String money){
		Intent pay = new Intent();
		pay.setClass(WebViewActivity4.this, LivePayActivity.class);
		pay.putExtra("name", title);
		pay.putExtra("commodityid", commodityid);
		pay.putExtra("money", money);
		WebViewActivity4.this.startActivityForResult(pay, STATE_TYPE_2);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, arg2);
		switch (requestCode) {
		case STATE_TYPE_2:
			videowebview.loadUrl(url+"&APP=android&uid="+LoginInfo.getInstance().getUserId());
//			videowebview.reload();
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (inCustomView()) {
				hideCustomView();
				return true;
			} else {
				videowebview.loadUrl("about:blank");
				WebViewActivity4.this.finish();
				Log.i("testwebview", "===>>>2");
			}
		}
		return false;
	}

	/**
	 * 判断是否是全屏
	 * 
	 * @return
	 */
	public boolean inCustomView() {
		return (xCustomView != null);
	}

	/**
	 * 全屏时按返加键执行退出全屏方法
	 */
	public void hideCustomView() {
		xwebchromeclient.onHideCustomView();
	}

	/**
	 * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
	 * 
	 * @author
	 */
	public class xWebChromeClient extends WebChromeClient {
		private Bitmap xdefaltvideo;
		private View xprogressvideo;

		@Override
		// 播放网络视频时全屏会被调用的方法
		public void onShowCustomView(View view,
				WebChromeClient.CustomViewCallback callback) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			videowebview.setVisibility(View.GONE);
			// 如果一个视图已经存在，那么立刻终止并新建一个
			if (xCustomView != null) {
				callback.onCustomViewHidden();
				return;
			}

			videoview.addView(view);
			xCustomView = view;
			xCustomViewCallback = callback;
			videoview.setVisibility(View.VISIBLE);
		}

		@Override
		// 视频播放退出全屏会被调用的
		public void onHideCustomView() {

			if (xCustomView == null)// 不是全屏播放状态
				return;

			// Hide the custom view.
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			xCustomView.setVisibility(View.GONE);

			// Remove the custom view from its container.
			videoview.removeView(xCustomView);
			xCustomView = null;
			videoview.setVisibility(View.GONE);
			xCustomViewCallback.onCustomViewHidden();

			videowebview.setVisibility(View.VISIBLE);

			// Log.i(LOGTAG, "set it to webVew");
		}

		// 视频加载添加默认图标
		@Override
		public Bitmap getDefaultVideoPoster() {
			// Log.i(LOGTAG, "here in on getDefaultVideoPoster");
			if (xdefaltvideo == null) {
				xdefaltvideo = BitmapFactory.decodeResource(getResources(),
						R.drawable.ic_launcher);
			}
			return xdefaltvideo;
		}

		// 视频加载时进程loading
		@Override
		public View getVideoLoadingProgressView() {
			// Log.i(LOGTAG, "here in on getVideoLoadingPregressView");

			if (xprogressvideo == null) {
				LayoutInflater inflater = LayoutInflater
						.from(WebViewActivity4.this);
				xprogressvideo = inflater.inflate(
						R.layout.video_loading_progress, null);
			}
			return xprogressvideo;
		}

		// 网页标题
		@Override
		public void onReceivedTitle(WebView view, String title) {
			(WebViewActivity4.this).setTitle(title);
		}
		
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			progressBar.setProgress(newProgress);
//			progressBar.setMessage("Loading..."+newProgress+"%");
			progressBar.setMessage("加载中..."+newProgress+"%");
			if(newProgress>=100)
				progressBar.dismiss();
			
			super.onProgressChanged(view, newProgress);
		}
	}

//	/**
//	 * 处理各种通知、请求等事件
//	 * 
//	 * @author
//	 */
//	public class xWebViewClientent extends WebViewClient {
//
//		@Override
//		public boolean shouldOverrideUrlLoading(WebView view, String url) {
//			Log.i("webviewtest", "shouldOverrideUrlLoading: " + url);
//			return false;
//		}
//		@Override
//		public void onPageStarted(WebView view, String url, Bitmap favicon) {
//			progressBar.show();
//			super.onPageStarted(view, url, favicon);
//		}
//
//		@Override
//		public void onPageFinished(WebView view, String url) {
//			if(progressBar.isShowing()){
//				progressBar.dismiss();
//			}
//			super.onPageFinished(view, url);
//		}
//		
//		
//	}
	/**
	 * 处理各种通知、请求等事件
	 * 
	 * @author
	 */
	public class xWebViewClientent extends BridgeWebViewClient {

		public xWebViewClientent(BridgeWebView webView) {
			super(webView);
		// TODO Auto-generated constructor stub
		}
		
//		@Override
//		public boolean shouldOverrideUrlLoading(WebView view, String url) {
//			Logger.i(TAG, "shouldOverrideUrlLoading: " + url);
//			return false;
//		}
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			progressBar.show();
			super.onPageStarted(view, url, favicon);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			if(progressBar.isShowing()){
				progressBar.dismiss();
			}
			super.onPageFinished(view, url);
		}	
		
	}
	
	/**
	 * 当横竖屏切换时会调用该方法
	 * 
	 * @author
	 *//*
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		Log.i("testwebview", "=====<<<  onConfigurationChanged  >>>=====");
		super.onConfigurationChanged(newConfig);

		if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
			Log.i("webview", "   现在是横屏1");
			islandport = false;
		} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
			Log.i("webview", "   现在是竖屏1");
			islandport = true;
		}
	}*/
	
	@Override
	protected void onPause() {
		videowebview.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		videowebview.onResume();
	}
	
	private CustomShareSheetDialog mSharedialog;
	private IWXAPI api;
	private String title = "";
	/**分享*/
	private void showShareBack(){
		clickStatistics(Constant.SHARE_ID,"视频详情页的分享");
		
			mSharedialog = new CustomShareSheetDialog(this,2);
			mSharedialog.setOnShareSheetItemClick(new OnShareSheetItemClick(){

				@Override
				public void onClick(int shareType) {
					if (mSharedialog != null && mSharedialog.isShowing()) {
						mSharedialog.dismiss();
					}
					mSharedialog = null;
					switch(shareType){
					case CustomShareSheetDialog.TYPE_WEIXIN:
						if(api.isWXAppInstalled()){
							onkeyshareWEiXin(1);
						}else{
							ToastAlone.showToast(WebViewActivity4.this, "亲，您尚未安装微信客户端，请下载安装~", 1);
						}
						break;
					
					case CustomShareSheetDialog.TYPE_WEIXIN_MOMENTS:
						if(api.isWXAppInstalled()){
							onkeyshareWEiXin(0);
						}else{
							ToastAlone.showToast(WebViewActivity4.this, "亲，您尚未安装微信客户端，请下载安装~", 1);
						}
						
						break;
					}
					
				}});
//		}
		mSharedialog.show();
	}
	
	/**分享到微信0:朋友圈，1 微信好友*/
	private void onkeyshareWEiXin(int type){
			
			String content = "\""+title+"\""+"点此播放"+"\""+url+"\""+"（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			WXVideoObject video = new WXVideoObject();
			video.videoUrl = url;
			WXMediaMessage msg = new WXMediaMessage(video);
			msg.title = title;
//			msg.description = videoInfo.getDetail();
			msg.description = content;
			
			Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
			msg.thumbData = com.v1.video.util.Util.bmpToByteArray(thumb, true);
			
			SendMessageToWX.Req req = new SendMessageToWX.Req();
			req.transaction = buildTransaction("video");
			req.message = msg;
			req.scene = type == 0?SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
//			req.scene = isTimelineCb.isChecked() ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneSession;
			api.sendReq(req);
			Constant.setShare(true);
			Constant.listenerShare.init(WebViewActivity4.this,null);
	}
	private String buildTransaction(final String type) {
		return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
	}
	
	/**
	 * QQ空间和QQ
	 * 
	 * @param v
	 * @param plat
	 */
	private void onkeyshareQQ(View v, Platform plat) {
			
			String content = "\""+title+"\""+"点此播放"+"\""+url+"\""+"（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			ShareParams sp = new ShareParams();
			// sp.setShareType(Platform.SHARE_VIDEO);
//			sp.setShareType(Platform.SHARE_WEBPAGE);
			sp.setShareType(Platform.SHARE_IMAGE);
			sp.setTitle(title);
//			 sp.setTitleUrl("i.apps.v1.cn");
			 sp.setTitleUrl(url);
			sp.setText(content);
//			sp.setUrl(url);
			Logger.i("json", "拍客视频url="+url);

			sp.setImageUrl(Constant.LOGO_ICON_URL);
			plat.setPlatformActionListener(new SharePlatformActionListener(
					WebViewActivity4.this, null));
			plat.share(sp);
	}
	
	/**
	 * 分享弹出框
	 * 
	 * @param context
	 * @param id
	 * @param type 0:新浪，1，腾讯微博 2，两个一起
	 */
	public void showSharedDialog(final Context context,final int type) {
		View shareView = View.inflate(context, R.layout.dialog_one_key_share,
				null);
		final Dialog dialog = new Dialog(context, R.style.dialog_custom);
		Display display = getWindowManager().getDefaultDisplay();
		int width = display.getWidth();
		LayoutParams params = new LayoutParams((int) (width * 0.9),
				ViewGroup.LayoutParams.MATCH_PARENT);
		dialog.setContentView(shareView, params);
		dialog.setCancelable(true);//8251

		final EditText contentEt = (EditText) shareView
				.findViewById(R.id.tv_shared_content);
		final TextView contentNum = (TextView) shareView
				.findViewById(R.id.tv_content_num);

		final View qqSelect = shareView.findViewById(R.id.rl_qq_share);
		String content1 = "\""+title+"\""+"点此播放"+"\""+url+"\""+"（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
		contentEt.setText(content1);
		qqSelect.setVisibility(View.GONE);
		
		if (!title.equals("")) {
			String number = Utils.calculateLength(title) + "/"
					+ TEXT_LENGTH;
			contentNum.setText(number);
		} else {
			contentNum.setText("0/" + TEXT_LENGTH);
		}

		contentEt.addTextChangedListener(new TextWatcher() {
			private CharSequence temp;
			private int selectionStart;
			private int selectionEnd;

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				temp = s;
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				String number = Utils.calculateLength(s) + "/" + TEXT_LENGTH;
				contentNum.setText(number);
				selectionStart = contentEt.getSelectionStart();
				selectionEnd = contentEt.getSelectionEnd();
				if (Utils.calculateLength(temp) > TEXT_LENGTH) {
					s.delete(
							(selectionStart - (int) (Utils.calculateLength(s) - TEXT_LENGTH)),
							selectionEnd);
					contentEt.setText(s);
					contentEt.setSelection(selectionStart);// 设置光标
				}
			}
		});

		
		shareView.findViewById(R.id.tv_share).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						String contentStr = contentEt.getText().toString()
								.trim();
						
						if (!TextUtils.isEmpty(contentStr)) {
							
								onkeyshare(v, ShareSDK.getPlatform(
										WebViewActivity4.this,
										SinaWeibo.NAME), contentStr);
								dialog.dismiss();
							
						} 
					}
				});
		shareView.findViewById(R.id.close_account_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
		shareView.findViewById(R.id.iv_cleanup).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						contentEt.setText("");
						contentNum.setText("0/" + TEXT_LENGTH);
					}
				});
		
		dialog.show();
	}
	
	/**
	 * sina微博，tencent微博
	 * 
	 * @param v
	 * @param plat
	 * @param content
	 */
	private void onkeyshare(View v, Platform plat, String content) {
			String shareV1 = "#第一视频#@第一视频 ";
			// String url
			// =Constant.PAIKE_VIDEO_SHARE_URL+videoInfo.getImgUrl()+"&videoURL="+videoInfo.getVideoUrl();
			String content1 = "\""+title+"\""+"点此播放"+"\""+url+"\""+"（通过＃第一视频＃分享，@第一视频，聚合全球海量有趣有料有用的精选短视频，助你大开眼界！下载猛戳http://apps.v1.cn）";
			ShareParams sp = new ShareParams();

			sp.setShareType(Platform.SHARE_IMAGE);
//			sp.setShareType(Platform.SHARE_WEBPAGE);
//			if(videoInfo.getWabSiteUrl() != null && videoInfo.getWabSiteUrl().length() > 5){
//				sp.setText(shareV1 + content + videoInfo.getWabSiteUrl());
//			}else{
//				sp.setText(shareV1 + content + videoInfo.getVideoUrl());
//			}
//			sp.setTitle(content1);
			sp.setText(content);
			sp.setImageUrl(Constant.LOGO_ICON_URL); // 直接分享网络地址
			plat.setPlatformActionListener(new SharePlatformActionListener(
					WebViewActivity4.this,null));
			plat.share(sp);
	}
	
	private void getMoneyFromServerOfVR(){
		String url = V1VideoHttpApi.GET_MONEY_FOR_VR_LIVE_OF_NVYOU() + "&devid="+Constant.DEVICEID+"&commodityid="+commodityid;
    	Logger.i(TAG, "查询VR付费数据Url ="+url);
    	
		RequestManager.getInstance().getRequest(WebViewActivity4.this, url, null, VrLiveMoneyEntity.class, 0, "WebViewActivity4", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				clearDialog();
				if(object != null){
					VrLiveMoneyEntity entity = (VrLiveMoneyEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(WebViewActivity4.this, "未知错误", Toast.LENGTH_SHORT);
						
//						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(WebViewActivity4.this, header.getMessage(), Toast.LENGTH_SHORT);
						
//						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							gotoLivePay(entity.getBody().getAmounts());					
						}else{
							toast(header.getMessage());
						}
					}else if(header.getStatus().equals("-1")){
						
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				clearDialog();
			}
		});
    }
	
	
	/***
     * 查询VR是否付费直播
     */
    private void getDataFromServerForVrLive(){
    	String url = V1VideoHttpApi.GET_INFO_FOR_VR_LIVE_OF_NUYOU() + "&devid="+Constant.DEVICEID+"&uid="+LoginInfo.getInstance().getUserId()
				+"&commodityid="+commodityid;
    	Logger.i(TAG, "查询VR是否付费直播Url ="+url);
    	
		RequestManager.getInstance().getRequest(WebViewActivity4.this, url, null, VrLivePayEntity.class, 0, "FragmentStarPeopleListAll", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				clearDialog();
				if(object != null){
					VrLivePayEntity entity = (VrLivePayEntity)object;
					com.v1.video.domain.BaseEntity.Header header = entity.getHeader();
					if(header == null){
						ToastAlone.showToast(WebViewActivity4.this, "未知错误", Toast.LENGTH_SHORT);
						
//						return;
					}else if(!header.getStatus().equals("1")){
						ToastAlone.showToast(WebViewActivity4.this, header.getMessage(), Toast.LENGTH_SHORT);
						
//						return;
					}else if(header.getStatus().equals("1")){
						if(entity.getBody() != null){
							processAskPayVR(entity.getBody().getIspay(),entity.getBody().getIslive(),entity.getBody().getPlayurl());					
						}else{
//							toast(header.getMessage());
						}
					}else if(header.getStatus().equals("-1")){
						
					}
				}
				
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i(TAG, message);
				clearDialog();
			}
		});
    }
    private ProgressDialog progDialog;
    private void showDialog(){
    	progDialog = Utils.getProgressDialog(WebViewActivity4.this,"加载中请稍候……");
    	progDialog.show();
    }
    
    private void clearDialog(){
    	if(progDialog != null){
    		progDialog.dismiss();
    		progDialog = null;
    	}
    }
    
    private void processAskPayVR(String isPay,String isLive,String url){
    	if(LoginInfo.getInstance().isLogin()){
    		if(isPay.equals("1") && isLive.equals("1")){
    			Intent intent = new Intent();
    			intent.setClass(WebViewActivity4.this, LiveVRPlayerActivity.class);
    			intent.putExtra("videourl", url);
    			WebViewActivity4.this.startActivity(intent);
    			return;
    		}
    	}
    	Intent intent = new Intent();
		intent.setClass(WebViewActivity4.this, VideoPlayerVRActivity.class);
		intent.putExtra("videourl", url);
		WebViewActivity4.this.startActivity(intent);
    }

}
